package routes

import (
	"github.com/garyburd/redigo/redis"
	"github.com/martini-contrib/render"
	"log"
	"net/http"
	"oceanserv"
	"rhelper"
	"strconv"
)

func GetControllerMgr(r render.Render, req *http.Request) {
	var controllerId = req.URL.Query().Get("id")
	conn := rhelper.Pool().Get()
	defer conn.Close()

	type RenderValue struct {
		Onlines  []string
		Offlines []string
	}

	var renderValue RenderValue = RenderValue{Onlines: []string{}, Offlines: []string{}}

	keys, err := redis.Strings(conn.Do("KEYS", rhelper.ControllerHash+"*"))
	if err != nil {
		log.Println(err)
		keys = []string{}
	}

	if len(keys) > 0 {
		renderValue.Offlines = make([]string, len(keys))
		renderValue.Onlines = make([]string, len(keys))
	}

	a := 0
	b := 0
	for _, key := range keys {
		id, err := redis.String(conn.Do("HGET", key, "id"))
		if id == "" || err != nil {
			continue
		}

		iid2, err := strconv.Atoi(id)
		if err != nil {
			continue
		}

		iid := int32(iid2)
		if oceanserv.GetControllerById(iid) != nil {
			renderValue.Onlines[a] = id
			a++
		} else {
			renderValue.Offlines[b] = id
			b++
		}
	}

	renderValue.Onlines = renderValue.Onlines[:a]
	renderValue.Offlines = renderValue.Offlines[:b]

	r.HTML(200, "controllerMgr", TmplValue{Title: "Controller manange", ExtValue: renderValue, ExtValue2: controllerId})
}

func GetControllerInfo(r render.Render, req *http.Request) {
	var controllerId = req.URL.Query().Get("controllerId")

	conn := rhelper.Pool().Get()
	defer conn.Close()

	type Controller struct {
		Err     string `json:"err"`
		Id      string `json:"id"`
		AppType string `json:"apptype"`
		Type    string `json:"type"`
		Account string `json:"account"`
		Farm    string `json:"farm"`
	}

	var controller = Controller{}
	infos, err := redis.Strings(conn.Do("HMGET", rhelper.ControllerHash+controllerId, "id", "apptype", "type", "account", "farm"))
	if err != nil {
		log.Println(err)
		controller.Err = err.Error()
	}

	if len(infos) > 0 && infos[0] != "" {
		controller.Id = infos[0]
		controller.AppType = infos[1]
		controller.Type = infos[2]
		controller.Account = infos[3]
		controller.Farm = infos[4]
	} else {
		controller.Err = "no data for controller:" + controllerId
	}

	r.JSON(200, controller)
}
